package models

import (
	"time"

	"gorm.io/gorm"
)

// KnowledgeBase 知识库模型
type KnowledgeBase struct {
	ID          uint           `json:"id" gorm:"primarykey"`
	Name        string         `json:"name" gorm:"not null;size:200"`
	Description string         `json:"description" gorm:"size:1000"`
	Type        string         `json:"type" gorm:"not null;size:50"` // document, qa, hybrid
	Config      string         `json:"config" gorm:"type:jsonb"`     // 配置参数
	Status      string         `json:"status" gorm:"default:active"` // active, inactive, processing
	IndexName   string         `json:"index_name" gorm:"size:100"`   // Elasticsearch索引名
	Collection  string         `json:"collection" gorm:"size:100"`   // Milvus集合名
	CreatedBy   uint           `json:"created_by"`
	UpdatedBy   uint           `json:"updated_by"`
	CreatedAt   time.Time      `json:"created_at"`
	UpdatedAt   time.Time      `json:"updated_at"`
	DeletedAt   gorm.DeletedAt `json:"-" gorm:"index"`

	// 关联
	Documents []Document `json:"documents,omitempty" gorm:"foreignKey:KnowledgeBaseID"`
}

// Document 文档模型
type Document struct {
	ID              uint           `json:"id" gorm:"primarykey"`
	KnowledgeBaseID uint           `json:"knowledge_base_id" gorm:"not null"`
	Title           string         `json:"title" gorm:"not null;size:500"`
	Content         string         `json:"content" gorm:"type:text"`
	ContentType     string         `json:"content_type" gorm:"size:50"` // text, markdown, html, pdf
	Source          string         `json:"source" gorm:"size:500"`      // 来源URL或文件路径
	Language        string         `json:"language" gorm:"default:zh;size:10"`
	Size            int64          `json:"size" gorm:"default:0"`           // 文档大小（字节）
	WordCount       int            `json:"word_count" gorm:"default:0"`     // 字数
	ChunkCount      int            `json:"chunk_count" gorm:"default:0"`    // 分块数量
	Status          string         `json:"status" gorm:"default:pending"`   // pending, processing, completed, failed
	ProcessingLog   string         `json:"processing_log" gorm:"type:text"` // 处理日志
	Metadata        string         `json:"metadata" gorm:"type:jsonb"`      // 元数据
	EmbeddingModel  string         `json:"embedding_model" gorm:"size:100"` // 使用的嵌入模型
	LastProcessedAt *time.Time     `json:"last_processed_at"`
	CreatedBy       uint           `json:"created_by"`
	UpdatedBy       uint           `json:"updated_by"`
	CreatedAt       time.Time      `json:"created_at"`
	UpdatedAt       time.Time      `json:"updated_at"`
	DeletedAt       gorm.DeletedAt `json:"-" gorm:"index"`

	// 关联
	KnowledgeBase KnowledgeBase `json:"knowledge_base,omitempty" gorm:"foreignKey:KnowledgeBaseID"`
	Chunks        []Chunk       `json:"chunks,omitempty" gorm:"foreignKey:DocumentID"`
}

// Chunk 文档分块模型
type Chunk struct {
	ID            uint           `json:"id" gorm:"primarykey"`
	DocumentID    uint           `json:"document_id" gorm:"not null"`
	Content       string         `json:"content" gorm:"type:text;not null"`
	ChunkIndex    int            `json:"chunk_index" gorm:"not null"`   // 在文档中的序号
	StartPos      int            `json:"start_pos" gorm:"default:0"`    // 在原文档中的起始位置
	EndPos        int            `json:"end_pos" gorm:"default:0"`      // 在原文档中的结束位置
	Size          int            `json:"size" gorm:"default:0"`         // 分块大小（字符数）
	WordCount     int            `json:"word_count" gorm:"default:0"`   // 字数
	EmbeddingHash string         `json:"embedding_hash" gorm:"size:64"` // 向量哈希值
	VectorID      string         `json:"vector_id" gorm:"size:100"`     // Milvus中的向量ID
	Metadata      string         `json:"metadata" gorm:"type:jsonb"`    // 元数据
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `json:"-" gorm:"index"`

	// 关联
	Document Document `json:"document,omitempty" gorm:"foreignKey:DocumentID"`
}

// QASession 问答会话模型
type QASession struct {
	ID              uint           `json:"id" gorm:"primarykey"`
	SessionID       string         `json:"session_id" gorm:"uniqueIndex;not null;size:100"`
	KnowledgeBaseID uint           `json:"knowledge_base_id" gorm:"not null"`
	UserID          uint           `json:"user_id"`
	Title           string         `json:"title" gorm:"size:200"`
	Status          string         `json:"status" gorm:"default:active"` // active, ended
	Config          string         `json:"config" gorm:"type:jsonb"`     // 会话配置
	CreatedAt       time.Time      `json:"created_at"`
	UpdatedAt       time.Time      `json:"updated_at"`
	DeletedAt       gorm.DeletedAt `json:"-" gorm:"index"`

	// 关联
	KnowledgeBase KnowledgeBase `json:"knowledge_base,omitempty" gorm:"foreignKey:KnowledgeBaseID"`
	Messages      []QAMessage   `json:"messages,omitempty" gorm:"foreignKey:SessionID;references:SessionID"`
}

// QAMessage 问答消息模型
type QAMessage struct {
	ID             uint           `json:"id" gorm:"primarykey"`
	SessionID      string         `json:"session_id" gorm:"not null;size:100"`
	MessageType    string         `json:"message_type" gorm:"not null;size:20"` // question, answer
	Content        string         `json:"content" gorm:"type:text;not null"`
	Sources        string         `json:"sources" gorm:"type:jsonb"`        // 引用的源文档
	Confidence     float64        `json:"confidence" gorm:"default:0"`      // 置信度
	TokenCount     int            `json:"token_count" gorm:"default:0"`     // 令牌数量
	ProcessingTime int64          `json:"processing_time" gorm:"default:0"` // 处理时间（毫秒）
	Metadata       string         `json:"metadata" gorm:"type:jsonb"`       // 元数据
	CreatedAt      time.Time      `json:"created_at"`
	UpdatedAt      time.Time      `json:"updated_at"`
	DeletedAt      gorm.DeletedAt `json:"-" gorm:"index"`

	// 关联
	Session QASession `json:"session,omitempty" gorm:"foreignKey:SessionID;references:SessionID"`
}

// SearchHistory 搜索历史模型
type SearchHistory struct {
	ID              uint           `json:"id" gorm:"primarykey"`
	KnowledgeBaseID uint           `json:"knowledge_base_id" gorm:"not null"`
	UserID          uint           `json:"user_id"`
	Query           string         `json:"query" gorm:"not null;size:1000"`
	SearchType      string         `json:"search_type" gorm:"not null;size:50"` // semantic, hybrid, similarity
	ResultCount     int            `json:"result_count" gorm:"default:0"`
	ProcessingTime  int64          `json:"processing_time" gorm:"default:0"` // 处理时间（毫秒）
	CreatedAt       time.Time      `json:"created_at"`
	DeletedAt       gorm.DeletedAt `json:"-" gorm:"index"`

	// 关联
	KnowledgeBase KnowledgeBase `json:"knowledge_base,omitempty" gorm:"foreignKey:KnowledgeBaseID"`
}

// TableName 指定表名
func (KnowledgeBase) TableName() string {
	return "knowledge_bases"
}

func (Document) TableName() string {
	return "documents"
}

func (Chunk) TableName() string {
	return "chunks"
}

func (QASession) TableName() string {
	return "qa_sessions"
}

func (QAMessage) TableName() string {
	return "qa_messages"
}

func (SearchHistory) TableName() string {
	return "search_history"
}
